using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    public class Ble
      : ConditionalBranchInstruction
    {
        private enum BleInstructionKind
        {
            None,   // error
            ble,    // branch if greater
            bled    // branch if greater with delay
        }

        private BleInstructionKind kind;

        public override int CycleCount
        {
            get
            {
                if (BranchStatus == BranchInstructionCycleCountStatus.BranchTaken)
                    return 1;
                else
                    return kind == BleInstructionKind.bled ? 2 : 3;
            }
        }

        public Ble()
            : base("ble")
        {
        }

        public override void Set(uint address, uint value)
        {
            base.Set(address, value);

            kind =
              DestinationRegister == 0x13 ? BleInstructionKind.bled :
              DestinationRegister == 0x03 ? BleInstructionKind.ble :
              BleInstructionKind.None;

            if (kind == BleInstructionKind.None)
                throw new UnknownInstructionException(value);
        }

        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            int sa = (int)MicroblazeComponent.ReadRegister(SourceRegisterA);
            uint sb = MicroblazeComponent.ReadRegister(SourceRegisterB);

            if (sa <= 0)
            {
                MicroblazeComponent.Pc = MicroblazeComponent.Pc + sb;
                BranchStatus = BranchInstructionCycleCountStatus.BranchTaken;

                if (kind == BleInstructionKind.bled)
                    MicroblazeComponent.DelayedBranchActive = true;
            }
            else
            {
                MicroblazeComponent.Pc += 4;
                BranchStatus = BranchInstructionCycleCountStatus.BranchNotTaken;
            }
        }

        public override string ToString()
        {
            return string.Format("{0} r{1}, r{2}",
              kind,
              SourceRegisterA,
              SourceRegisterB
            );
        }
    }
}
